<?php
session_start();

if (!isset($_SESSION['admin_logged_in']) || !$_SESSION['admin_logged_in']) {

    header('Location: index.php');
    exit;
}

require_once __DIR__ . '/../core/config.php';

try {
    $db = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=' . DB_CHARSET, DB_USER, DB_PASS);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo '数据库连接失败：' . htmlspecialchars($e->getMessage());
    exit;
}

// 获取分类列表
try {
    $stmt = $db->query("SELECT c.*, COUNT(pc.plugin_id) as plugin_count FROM categories c LEFT JOIN plugin_categories pc ON c.id = pc.category_id GROUP BY c.id ORDER BY c.sort_order, c.name");
    $categories = $stmt->fetchAll(PDO::FETCH_ASSOC);
   
} catch (PDOException $e) {
    echo '<div class=\"bg-red-100 text-red-700 p-4 rounded mb-4\">SQL错误：' . htmlspecialchars($e->getMessage()) . '</div>';
    exit;
}

?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>分类管理 - 幻影工具网</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#3B82F6',
                        secondary: '#6366F1'
                    }
                }
            }
        }
    </script>
</head>
<body class="bg-gray-50 min-h-screen">
    <!-- 顶部导航 -->
    <nav class="bg-white shadow-sm border-b border-gray-200 sticky top-0 z-10">
        <div class="max-w-7xl mx-auto px-4 flex justify-between items-center h-16">
            <h1 class="text-xl font-bold text-blue-700">幻影工具网后台</h1>
            <div class="flex items-center space-x-4">
                <a href="/" class="text-gray-600 hover:text-blue-700">返回前台</a>
                <a href="logout.php" class="text-red-600 hover:text-red-800">退出登录</a>
            </div>
        </div>
    </nav>

    <div class="flex min-h-screen">
        <!-- 侧边栏 -->
        <aside class="w-64 bg-white shadow-md hidden md:block">
            <nav class="mt-8 space-y-2 px-4">
                <a href="index.php" class="block px-4 py-2 rounded-lg text-gray-600 hover:bg-blue-50 hover:text-blue-700">仪表盘</a>
                <a href="plugins.php" class="block px-4 py-2 rounded-lg text-gray-600 hover:bg-blue-50 hover:text-blue-700">插件管理</a>
                <a href="categories.php" class="block px-4 py-2 rounded-lg bg-blue-50 text-blue-700 font-bold">分类管理</a>
                <a href="stats.php" class="block px-4 py-2 rounded-lg text-gray-600 hover:bg-blue-50 hover:text-blue-700">数据统计</a>
                <a href="logs.php" class="block px-4 py-2 rounded-lg text-gray-600 hover:bg-blue-50 hover:text-blue-700">操作日志</a>
            </nav>
        </aside>
        <!-- 主内容区 -->
        <main class="flex-1 p-6">
            <div class="mb-8">
                <h2 class="text-2xl font-bold text-gray-900 mb-2">分类管理</h2>
                <p class="text-gray-500">管理插件分类，包括添加、编辑、删除分类</p>
            </div>
            <!-- 操作按钮 -->
            <div class="mb-6 flex flex-wrap gap-4">
                <button onclick="openAddModal()" class="bg-blue-600 text-white px-5 py-2 rounded-lg shadow hover:bg-blue-700 transition">添加分类</button>
            </div>
            <!-- 分类列表 -->
            <div class="bg-white rounded-xl shadow p-4 overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200">
                    <thead class="bg-gray-50">
                        <tr>
                            <th class="px-6 py-3 text-left text-xs font-bold text-gray-500 uppercase">分类信息</th>
                            <th class="px-6 py-3 text-left text-xs font-bold text-gray-500 uppercase">插件数量</th>
                            <th class="px-6 py-3 text-left text-xs font-bold text-gray-500 uppercase">排序</th>
                            <th class="px-6 py-3 text-left text-xs font-bold text-gray-500 uppercase">操作</th>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-100">
                        <?php foreach ($categories as $category): ?>
                        <tr>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <div class="flex items-center">
                                    <div class="h-10 w-10 rounded-lg bg-gradient-to-br from-blue-400 to-purple-500 flex items-center justify-center">
                                        <span class="text-white font-bold text-lg"><?php echo mb_substr($category['name'], 0, 1); ?></span>
                                    </div>
                                    <div class="ml-4">
                                        <div class="text-sm font-bold text-gray-900"><?php echo htmlspecialchars($category['name']); ?></div>
                                        <div class="text-xs text-gray-500"><?php echo htmlspecialchars($category['description']); ?></div>
                                    </div>
                                </div>
                            </td>
                            <td class="px-6 py-4 text-sm text-gray-500"><?php echo htmlspecialchars($category['plugin_count']); ?> 个插件</td>
                            <td class="px-6 py-4 text-sm text-gray-500"><?php echo htmlspecialchars($category['sort_order']); ?></td>
                            <td class="px-6 py-4 text-sm font-medium">
                                <div class="flex space-x-2">
                                    <button onclick="editCategory(<?php echo $category['id']; ?>)" class="text-blue-600 hover:text-blue-900">编辑</button>
                                    <button onclick="deleteCategory(<?php echo $category['id']; ?>)" class="text-red-600 hover:text-red-900">删除</button>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            <!-- 添加/编辑分类模态框 -->
            <div id="categoryModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full hidden z-50">
                <div class="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white">
                    <div class="mt-3">
                        <h3 id="modalTitle" class="text-lg font-medium text-gray-900 mb-4">添加分类</h3>
                        <form id="categoryForm">
                            <input type="hidden" id="categoryId" name="id">
                            <div class="mb-4">
                                <label class="block text-sm font-medium text-gray-700 mb-2">分类名称</label>
                                <input type="text" id="categoryName" name="name" class="w-full border border-gray-300 rounded-md px-3 py-2" required>
                            </div>
                            <div class="mb-4">
                                <label class="block text-sm font-medium text-gray-700 mb-2">描述</label>
                                <textarea id="categoryDescription" name="description" rows="3" class="w-full border border-gray-300 rounded-md px-3 py-2"></textarea>
                            </div>
                            <div class="mb-4">
                                <label class="block text-sm font-medium text-gray-700 mb-2">排序</label>
                                <input type="number" id="categorySortOrder" name="sort_order" value="0" class="w-full border border-gray-300 rounded-md px-3 py-2">
                            </div>
                            <div class="flex justify-end space-x-3">
                                <button type="button" onclick="closeCategoryModal()" class="px-4 py-2 text-gray-600 border border-gray-300 rounded-md hover:bg-gray-50">取消</button>
                                <button type="submit" class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700">保存</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
            <script>
                // 添加分类
                function openAddModal() {
                    document.getElementById('modalTitle').textContent = '添加分类';
                    document.getElementById('categoryId').value = '';
                    document.getElementById('categoryName').value = '';
                    document.getElementById('categoryDescription').value = '';
                    document.getElementById('categorySortOrder').value = '0';
                    document.getElementById('categoryModal').classList.remove('hidden');
                }
                // 编辑分类
                function editCategory(id) {
                    fetch(`ajax.php?action=get_category&id=${id}`)
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                document.getElementById('modalTitle').textContent = '编辑分类';
                                document.getElementById('categoryId').value = data.category.id;
                                document.getElementById('categoryName').value = data.category.name;
                                document.getElementById('categoryDescription').value = data.category.description;
                                document.getElementById('categorySortOrder').value = data.category.sort_order;
                                document.getElementById('categoryModal').classList.remove('hidden');
                            } else {
                                alert('获取分类信息失败：' + data.message);
                            }
                        });
                }
                function closeCategoryModal() {
                    document.getElementById('categoryModal').classList.add('hidden');
                }
                // 表单提交
                document.getElementById('categoryForm').addEventListener('submit', function(e) {
                    e.preventDefault();
                    const formData = new FormData(this);
                    const id = document.getElementById('categoryId').value;
                    if (id) {
                        formData.append('action', 'edit_category');
                    } else {
                        formData.append('action', 'add_category');
                    }
                    fetch('ajax.php', {
                        method: 'POST',
                        body: formData
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            alert(id ? '分类更新成功！' : '分类添加成功！');
                            location.reload();
                        } else {
                            alert('操作失败：' + data.message);
                        }
                    });
                });
                // 删除分类
                function deleteCategory(id) {
                    if (confirm('确定要删除这个分类吗？此操作不可恢复。')) {
                        fetch('ajax.php', {
                            method: 'POST',
                            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                            body: `action=delete_category&id=${id}`
                        })
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                location.reload();
                            } else {
                                alert('删除失败：' + data.message);
                            }
                        });
                    }
                }
            </script>
        </main>
    </div>
<?php echo 'HTML END<br>'; ?>
</body>
</html> 